package com.cytech.cloudclinic.moudle.main.clinic.admission.prescription;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.PrescriptionAddDrugAdapter;
import com.cytech.cloudclinic.adapter.PrescriptionDrugMenuAdapter;
import com.cytech.cloudclinic.adapter.PrescriptionParentAdapter;
import com.cytech.cloudclinic.base.BaseFragment;
import com.cytech.cloudclinic.bean.Acupoint;
import com.cytech.cloudclinic.bean.CustomGroupDrug;
import com.cytech.cloudclinic.bean.CustomPrescriptionEntity;
import com.cytech.cloudclinic.bean.Drug;
import com.cytech.cloudclinic.bean.DrugTag;
import com.cytech.cloudclinic.bean.Patient;
import com.cytech.cloudclinic.bean.event.TollEvent;
import com.cytech.cloudclinic.bean.req.AddPrescription;
import com.cytech.cloudclinic.contract.PrescriptionTemplateContract;
import com.cytech.cloudclinic.dialog.AcuPointDialog;
import com.cytech.cloudclinic.dialog.AddDoctorOrderDialog;
import com.cytech.cloudclinic.dialog.BillTollDialog;
import com.cytech.cloudclinic.dialog.EditDrugBodyPointDialog;
import com.cytech.cloudclinic.dialog.EditDrugDefaultDialog;
import com.cytech.cloudclinic.dialog.EditDrugTimeDialog;
import com.cytech.cloudclinic.dialog.PrescriptionListDialog;
import com.cytech.cloudclinic.dialog.SelectUseAndDayDialog;
import com.yechaoa.yutils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 处方
 */
public class PrescriptionFragment extends BaseFragment<PrescriptionPresenter> implements PrescriptionView {
    @BindView(R.id.rv_menu_drug_tag)
    RecyclerView menuTagRv;
    @BindView(R.id.rv_prescription_drug)
    RecyclerView drugRv;
    @BindView(R.id.rv_prescription_parent)
    RecyclerView parentRv;

    private int drugParentTagId;
    private List<DrugTag> drugTags;
    private List<Drug> drugList;
    private List<CustomPrescriptionEntity> parentList;
    private PrescriptionDrugMenuAdapter drugMenuAdapter;
    private PrescriptionAddDrugAdapter drugAdapter;
    private PrescriptionParentAdapter parentAdapter;

    private int currentGroup = 0;
    //处方筏对应组下面的药品
    private int currentChildPos;

    private ActivityResultLauncher<Integer> myActivityLauncher;
    private AddPrescription prescription;
    private Patient patient;

    public static PrescriptionFragment newInstance(int drugParentTagId, AddPrescription prescription, Patient patient) {
        PrescriptionFragment fragment = new PrescriptionFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("drugParentTagId", drugParentTagId);
        bundle.putSerializable("prescription", prescription);
        bundle.putSerializable("patient", patient);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected PrescriptionPresenter createPresenter() {
        return new PrescriptionPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_admission_prescription;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        drugParentTagId = getArguments().getInt("drugParentTagId");
        prescription = (AddPrescription) getArguments().getSerializable("prescription");
        patient = (Patient) getArguments().getSerializable("patient");
        myActivityLauncher = registerForActivityResult(new PrescriptionTemplateContract(), new ActivityResultCallback<List<Drug>>() {
            @Override
            public void onActivityResult(List<Drug> result) {
                if (result != null) {
                    if (parentAdapter.getData().size() == 0) {
                        CustomPrescriptionEntity entity = new CustomPrescriptionEntity();
                        entity.drugList = result;
                        parentAdapter.addData(entity);
                    } else {
                        parentAdapter.getItem(currentGroup).drugList.addAll(result);
                        parentAdapter.notifyItemChanged(currentGroup);
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        initDrugMenuRv();

        initDrugListRV();

        initParentRv();

        presenter.getDrugTagList(drugParentTagId);
    }


    @Override
    public void getDrugChildTagSuccess(List<DrugTag> data) {
        //获取药品分类
        drugMenuAdapter.setNewInstance(data);
        if (data != null && data.size() > 0) {
            presenter.getDrugList("", data.get(0).tag_id);
        }
    }

    @Override
    public void getAcuPointSuccess(List<Acupoint> data) {
        //获取穴位
//        drugMenuAdapter.setNewInstance(drugTags);
//        drugMenuAdapter.notifyDataSetChanged();
//        if(data!=null&&data.size()>0){
//            presenter.getAcuPoint(false,data.get(0).acupoint_id,drugParentTagId,false);
//        }
    }

    @Override
    public void createBillSuccess(AddPrescription req, String prescriptionId, boolean isToll) {
        if (isToll) {
            //收费
            BillTollDialog billTollDialog = new BillTollDialog(prescription, prescriptionId);
            billTollDialog.show(getChildFragmentManager(), "bill");
        } else {
            //生成收费单
            PrescriptionListDialog createBillDialog = new PrescriptionListDialog(req, patient, prescriptionId);
            createBillDialog.show(getChildFragmentManager(), "prescriptionList");
        }
    }

    @Override
    public void getAcuPointContentSuccess(List<Acupoint> data) {
        drugAdapter.setNewInstance(drugList);
        drugAdapter.notifyDataSetChanged();
    }

    @Override
    public void getDrugSuccess(List<Drug> data) {
        //获取药品列表
        drugAdapter.setNewInstance(data);
    }

    /**
     * 初始化药品分类标签
     */
    private void initDrugMenuRv() {
        drugTags = new ArrayList<>();
        drugMenuAdapter = new PrescriptionDrugMenuAdapter(drugTags);
        menuTagRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        menuTagRv.setAdapter(drugMenuAdapter);
        drugMenuAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                drugMenuAdapter.setCurrentPos(position);
                presenter.getDrugList("", drugMenuAdapter.getItem(position).tag_id);
            }
        });
    }

    /**
     * 初始化药品列表
     */
    private void initDrugListRV() {
        drugList = new ArrayList<>();
        drugAdapter = new PrescriptionAddDrugAdapter(drugList);
        drugRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        drugRv.setAdapter(drugAdapter);

        drugAdapter.addChildClickViewIds(R.id.tv_prescription_add_drug);
        drugAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                //TODO 这里应该判断药品列表中如果存在同样的药品id，数量加1
                Drug drug = drugAdapter.getItem(position);
                drug.cont_unit_text = drug.subunit_text;
                if (parentAdapter.getItemCount() == 0) {
                    //0的话新增一个分组，最后一个的话也新增一个分组
                    CustomPrescriptionEntity newItem = new CustomPrescriptionEntity();
                    newItem.drugList.add(drugAdapter.getItem(position));
                    parentAdapter.addData(newItem);
                    parentAdapter.addData(new CustomPrescriptionEntity());
                } else {
                    //判断是否是新增的数据
                    boolean isNewAdd = true;
                    int existPos = -1;
                    List<Drug> currentGroupDrug = parentAdapter.getItem(currentGroup).drugList;
                    for (int i = 0; i < currentGroupDrug.size(); i++) {
                        //存在相同的id，数量加1即可，不必添加新的item
                        if (drug.drug_id == currentGroupDrug.get(i).drug_id) {
                            existPos = i;
                            isNewAdd = false;
                            break;
                        }
                    }
                    if (!isNewAdd) {
                        //列表里面已经有数据了
                        currentGroupDrug.get(existPos).count += 1;
                        parentAdapter.notifyItemChanged(currentGroup);
                    } else {
                        if (currentGroup == parentAdapter.getItemCount() - 1) {
                            parentAdapter.addData(new CustomPrescriptionEntity());

                            parentAdapter.getItem(currentGroup).drugList.add(drugAdapter.getItem(position));
                            parentAdapter.notifyItemChanged(currentGroup);
                        } else {
                            //添加药品到对于的适配器中
                            parentAdapter.getItem(currentGroup).drugList.add(drugAdapter.getItem(position));
                            parentAdapter.notifyItemChanged(currentGroup);
                        }
                    }
                }
            }
        });
    }

    /**
     * 初始化处方筏父标签（分组标签）
     */
    private void initParentRv() {
        parentList = new ArrayList<>();
        parentAdapter = new PrescriptionParentAdapter(parentList, presenter.isShowAcupoint(drugParentTagId), drugParentTagId,new PrescriptionParentAdapter.OnChildClickListener() {
            @Override
            public void acupointClick(int parentPos, int childPos) {
                currentGroup = parentPos;
                currentChildPos = childPos;
                //presenter.getAcuPoint(false,0,drugParentTagId,true);
                //弹出穴位选择弹窗
                AcuPointDialog acuPointDialog = new AcuPointDialog(drugParentTagId, parentAdapter.getItem(parentPos).drugList.get(childPos), new AcuPointDialog.OnSaveAcuPointListener() {
                    @Override
                    public void onSave(String acupointStr) {
                        parentAdapter.getItem(parentPos).drugList.get(childPos).acupoints.acupoint_name = acupointStr;
                        parentAdapter.notifyItemChanged(parentPos);
                    }
                });
                acuPointDialog.show(getChildFragmentManager(), "acupoint");
            }

            @Override
            public void acupointTime(int parentPos, int childPos) {
                EditDrugTimeDialog timeDialog = new EditDrugTimeDialog(drugParentTagId, parentAdapter.getItem(parentPos).drugList.get(childPos), new EditDrugTimeDialog.OnSaveClickListener() {
                    @Override
                    public void onSave(Drug drug) {
                        Drug oldDrug = parentAdapter.getItem(parentPos).drugList.get(childPos);
                        oldDrug.acupoints.acupoint_number = drug.acupoints.acupoint_number;
                        oldDrug.acupoints.acupoint_name = drug.acupoints.acupoint_name;
                        parentAdapter.notifyItemChanged(parentPos);
                    }
                });
                timeDialog.show(getFragmentManager(), "drugTime");
            }

            @Override
            public void drugItemClick(int parentPos, int childPos) {
                EditDrugDefaultDialog editDrugDialog = new EditDrugDefaultDialog(drugParentTagId, parentAdapter.getItem(parentPos).drugList.get(childPos), new EditDrugDefaultDialog.OnSaveClickListener() {
                    @Override
                    public void onSave(Drug drug) {
                        Drug oldDrug = parentAdapter.getItem(parentPos).drugList.get(childPos);
                        oldDrug.number = drug.number;
                        oldDrug.usage_mode = drug.usage_mode;
                        oldDrug.dosage = drug.dosage;
                        oldDrug.frequency = drug.frequency;
                        parentAdapter.notifyItemChanged(parentPos);
                    }
                });
                editDrugDialog.show(getFragmentManager(), "editdrug");
            }

            @Override
            public void bodyPointClick(int parentPos, int childPos) {
                //体位
                EditDrugBodyPointDialog editDrugDialog = new EditDrugBodyPointDialog(drugParentTagId, parentAdapter.getItem(parentPos).drugList.get(childPos), new EditDrugBodyPointDialog.OnSaveClickListener() {
                    @Override
                    public void onSave(Drug drug) {
                        Drug oldDrug = parentAdapter.getItem(parentPos).drugList.get(childPos);
                        oldDrug.bodyPoint = drug.bodyPoint;
                        oldDrug.bodyPointTimes = drug.bodyPointTimes;
                        parentAdapter.notifyItemChanged(parentPos);
                    }
                });
                editDrugDialog.show(getFragmentManager(), "editdrug");
            }
        });
        parentRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        parentRv.setAdapter(parentAdapter);
        parentAdapter.addChildClickViewIds(R.id.ll_item_prescription_group, R.id.item_doctor_order,R.id.ll_item_day_number);
        parentAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()) {
                    case R.id.ll_item_prescription_group:
                        currentGroup = position;
                        parentAdapter.setCurrentPos(position);
                        presenter.getDrugTagList(drugParentTagId);
                        break;
                    case R.id.item_doctor_order:
                        AddDoctorOrderDialog doctorOrderDialog = new AddDoctorOrderDialog(new AddDoctorOrderDialog.OnSaveDoctorListener() {
                            @Override
                            public void onSave(String doctorOrderStr) {
                                parentAdapter.getItem(position).doctorOrder = doctorOrderStr;
                                parentAdapter.notifyItemChanged(position);
                            }
                        });
                        doctorOrderDialog.show(getChildFragmentManager(), "doctorOrder");
                        break;
                    case R.id.ll_item_day_number:   //用法，天数，次数
                        SelectUseAndDayDialog useAndDayDialog = new SelectUseAndDayDialog(drugParentTagId);
                        useAndDayDialog.show(getChildFragmentManager(),"use_day");
                        break;
                }

            }
        });
    }

    @OnClick({R.id.btn_prescription_create_bill, R.id.tv_prescription_template, R.id.btn_prescription_temp_save, R.id.btn_prescription_toll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_prescription_create_bill:
                buildPrescription();
                presenter.addPrescription(prescription, false);
                break;
            case R.id.tv_prescription_template:
                myActivityLauncher.launch(drugParentTagId);
                break;
            case R.id.btn_prescription_temp_save:
                //临时保存
                break;
            case R.id.btn_prescription_toll:
                //收费，先生成处方，在根据处方id定位
                buildPrescription();
                presenter.addPrescription(prescription, true);
                break;
        }
    }

    /**
     * 构建处方
     */
    private void buildPrescription() {
        if (prescription != null) {
            prescription.status = 1;
            List<CustomPrescriptionEntity> templateDrugList = parentAdapter.getData();
            for (int i = 0; i < templateDrugList.size(); i++) {
                if (templateDrugList.get(i).drugList != null && templateDrugList.get(i).drugList.size() > 0) {
                    CustomGroupDrug groupDrug = new CustomGroupDrug();
                    groupDrug.doctors_advice = templateDrugList.get(i).doctorOrder;
                    groupDrug.list = templateDrugList.get(i).drugList;
                    prescription.drugs.add(groupDrug);
                }
            }
            Log.d("TAG", "onClick: " + prescription.toString());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void tollSuccessEvent(TollEvent event) {
        getActivity().finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
